package com.example.huanxin;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.NameList;

import com.boyuan.huijiaoyu.ChangeGroupnameActivity;
import com.boyuan.huijiaoyu.DelGroupMemberActivity;
import com.boyuan.huijiaoyu.DeleMember;
import com.boyuan.huijiaoyu.HomeContactDeail1Activity;
import com.boyuan.huijiaoyu.HomeContactDeail2Activity;
import com.boyuan.huijiaoyu.MyFriendActivity;
import com.boyuan.huijiaoyu.R;
import com.example.contactfragment.ContactGroupService;
import com.example.contactfragment.ContactService;
import com.example.contactfragment.GroupMember;
import com.example.contactfragment.HomeContactMyCaseGroupActivity;
import com.example.contactfragment.HomeContactMyGroupActivity;
import com.example.contactfragment.HomeContactOrgActivity;
import com.example.contactfragment.LognUser;
import com.example.newfragment.DetailPerson;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.CustomDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class GroupDetailActivity extends Activity implements OnClickListener{

	private String groupId;
	private String groupName;
	private ContactGroupService contactgroupService;
	ArrayList<GroupMember> groups = new ArrayList<GroupMember>();
	ArrayList<String> phonelist = new ArrayList<String>();
	ArrayList<String> usernamelist = new ArrayList<String>();
	ArrayList<String> memberlist = new ArrayList<String>();
	private GridView gridview;
	private MyAdapter adapter;
	boolean isgetGroupMember = false;
	private String yonghu;
	private Button btn_tuiqun;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	boolean isdel = false;
	boolean isclick = true;
	private String groudMemberID;
	boolean isgetidOK = false;
	private ContactService contactService;
	private DetailPerson homeContactDetailEntity;
	private String yonghuID;
	int nun;
	boolean isreqok = false;
	private TextView group_name;
	boolean isdelok = false;
	private TextView tv_title;
	private String caseid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_detail);
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		yonghu = sp.getString("username","");
		yonghuID = sp.getString("id", "");
		Intent intent = getIntent();
		groupId = intent.getStringExtra("groupId");
		groupName = intent.getStringExtra("groupName");
		caseid = intent.getStringExtra("caseid");
		btn_tuiqun = (Button) findViewById(R.id.btn_tuiqun);
		tv_title = (TextView) findViewById(R.id.group_name123);
		getGroupMemberCache();
		getGroupMember();
		initUI();
		
	}

	private void initUI() {
		group_name = (TextView) findViewById(R.id.group_name);
		findViewById(R.id.lay_groupname).setOnClickListener(this);
		group_name.setText(groupName);
		gridview = (GridView) findViewById(R.id.gridView1);
		adapter = new MyAdapter();
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
					long arg3) {
				Button btn_delmember = (Button) arg1.findViewById(R.id.imag_delgroupmember);
				ImageView iamg_tou = (ImageView) arg1.findViewById(R.id.imag_tou);
				if(arg2 <= phonelist.size()-1){
//					if(isdel == true){
//						if(phonelist.get(arg2).equals(yonghu)){
//							
//						}else{
//							delGroupMember(groupId, phonelist.get(arg2),arg2);
//						}
//					}else{
					getid(phonelist.get(arg2));
						new Handler().postDelayed(new Runnable() {
							
							@Override
							public void run() {
								if(isgetidOK == true){
									getContactDetail(groudMemberID);
									return;
								}else{
									new Handler().postDelayed(this, 1000);
								}
							}
						}, 1000);
						
//						finish();
//					}
					
				}else if(arg2 == phonelist.size()){
//					if(isdel == true){
//						
//					}else{
						Intent intent = new Intent();
						intent.setClass(GroupDetailActivity.this, MyFriendActivity.class);
						intent.putExtra("groupid", groupId);
						intent.putStringArrayListExtra("phonelist", phonelist);
						intent.putStringArrayListExtra("usernamelist", usernamelist);
						startActivityForResult(intent, 1);
//					}
				}else{
					isdel = !isdel;
					adapter.notifyDataSetChanged();
				}
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(data!=null){
			if(requestCode==1&&resultCode==2){
				phonelist.clear();
				usernamelist.clear();
				getGroupMember();
			}else if(requestCode==3&&resultCode==4){
				phonelist.clear();
				usernamelist.clear();
				getGroupMember();
			}else if(requestCode==5&&resultCode==6){
				String groupname1 = data.getStringExtra("groupname1");
				group_name.setText(groupname1);
			}
		}
	}
	
	class MyAdapter extends BaseAdapter{
		int i = 0;
		@Override
		public int getCount() {
			if(nun == 0){
				i = phonelist.size()+2;
			}else if(nun == 1){
				i = phonelist.size()+1;
			}else{
				i = 0;
			}
			return i;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			View inflate = getLayoutInflater().inflate(R.layout.grid_member, null);
			final TextView tv = (TextView) inflate.findViewById(R.id.textView1);
			ImageView imag_tou = (ImageView) inflate.findViewById(R.id.imag_tou);
			imageLoader = ImageLoader.getInstance();
			options = new DisplayImageOptions.Builder()
			.showImageOnLoading(R.drawable.default_header)
			.showImageForEmptyUri(R.drawable.default_header)
			.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
			.cacheOnDisc(true).considerExifParams(true)
			.build();
			final Button imag_del = (Button) inflate.findViewById(R.id.imag_delgroupmember);
			if(arg0<=phonelist.size()-1){
				String uri = Constant.photourl1 + phonelist.get(arg0);
				imageLoader.displayImage(uri, imag_tou, options);
				tv.setText(usernamelist.get(arg0));
				if(phonelist.get(arg0).equals(yonghu)){
					
				}else{
					if(isdel == true){
						imag_del.setVisibility(View.VISIBLE);
						imag_del.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								delGroupMember(groupId, phonelist.get(arg0),arg0);
								
							}
						});
					}else{
					imag_del.setVisibility(View.GONE);
					}
				}
			}else if(arg0 == phonelist.size()){
//				if(isdel == true){
//					imag_del.setVisibility(View.INVISIBLE);
//				}else{
//					imag_del.setVisibility(View.GONE);
//				}
				imag_tou.setImageResource(R.drawable.tianjia);
				tv.setText("");
			}else{
				imag_tou.setImageResource(R.drawable.shanchu);
				tv.setText("");
				for(int i=0;i<groups.size();i++){
					if(groups.get(i).getMember()==null){
						if(groups.get(i).getOwner().toString().equals(yonghu)){
							imag_tou.setVisibility(View.VISIBLE);
						}
					}else{
						if(groups.get(i).getMember().toString().equals(yonghu)){
							imag_tou.setVisibility(View.GONE);
							
						}
					}
				}
			}
			return inflate;
		}
		
	}
	
	/**
	 * 点击退出群组按钮
	 */
	public void exitGroup(View view) {
		for(int i=0;i<groups.size();i++){
			if(groups.get(i).getMember()==null){
				if(groups.get(i).getOwner().toString().equals(yonghu)){
					exitDeleGroup();
				}
			}else{
				if(groups.get(i).getMember().toString().equals(yonghu)){
					exitGroup();
				}
			}
		}
	}
	
	private void exitDeleGroup() {
		final CustomDialog dialog = new CustomDialog(this,
				R.style.qr_dialog);
		dialog.show();
		// 标题
		TextView tv_title = (TextView) dialog.findViewById(R.id.dialog_title);
		tv_title.setText("确定退出");
		// 内容
		TextView tv_content = (TextView) dialog
				.findViewById(R.id.dialog_content);
		tv_content.setVisibility(View.INVISIBLE);
		tv_content.setText("");
		// 右上角取消
		ImageView imag_cancel = (ImageView) dialog
				.findViewById(R.id.dialog_img_cancel);
		imag_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				
			}
		});
		// 确定按钮
		Button btn_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				dialog.cancel();
				deleGroup(groupId,yonghu);
				if(caseid != null){
					startActivity(new Intent(GroupDetailActivity.this,HomeContactMyCaseGroupActivity.class));
				}else{
					startActivity(new Intent(GroupDetailActivity.this,HomeContactMyGroupActivity.class));
				}
				finish();
				Intent intent = new Intent();
				intent.setAction(Constant.CloseChatAC);
				sendBroadcast(intent);
				Intent intent2 = new Intent();
				intent2.setAction("uptatagroup");
				sendBroadcast(intent2);
			}
		});
		// 取消按钮
		Button btn_cancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
	}
	

	private void exitGroup() {
		final CustomDialog dialog = new CustomDialog(this,
				R.style.qr_dialog);
		dialog.show();
		// 标题
		TextView tv_title = (TextView) dialog.findViewById(R.id.dialog_title);
		tv_title.setText("确定退出");
		// 内容
		TextView tv_content = (TextView) dialog
				.findViewById(R.id.dialog_content);
		tv_content.setVisibility(View.INVISIBLE);
		tv_content.setText("");
		// 右上角取消
		ImageView imag_cancel = (ImageView) dialog
				.findViewById(R.id.dialog_img_cancel);
		imag_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				
			}
		});
		// 确定按钮
		Button btn_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
		btn_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int a = 0;
				dialog.cancel();
				for (int i = 0; i < phonelist.size(); i++) {
					if(yonghu.equals(phonelist.get(i))){
						a = i;
					}
				}
				delGroupMember(groupId,yonghu,a);
				if(caseid != null){
					startActivity(new Intent(GroupDetailActivity.this,HomeContactMyCaseGroupActivity.class));
				}else{
					startActivity(new Intent(GroupDetailActivity.this,HomeContactMyGroupActivity.class));
				}
				finish();
				Intent intent = new Intent();
				intent.setAction(Constant.CloseChatAC);
				sendBroadcast(intent );
				Intent intent2 = new Intent();
				intent2.setAction("uptatagroup");
				sendBroadcast(intent2);
			}
		});
		// 取消按钮
		Button btn_cancel = (Button) dialog
				.findViewById(R.id.dialog_button_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
	}
	
	
	public void deleGroup(String id, String usernames){
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		
		contactgroupService.delGroup(id, new GetMultilParamsListener() {
			
			@Override
			public void onFinish(Object... params) {
				
			}
			
			@Override
			public void onFailed(String Message) {
				
			}
		});
		
	}
	
	public void delGroupMember(String id, final String usernames, final int posion){
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		
		contactgroupService.delGroupMember("1", id, usernames, new GetOneRecordListener<List<DeleMember>>() {

			@Override
			public void onFinish(List<DeleMember> data) {
				
			}

			@Override
			public void onFailed(String Message) {
				
			}
			
		}, new GetMultilParamsListener() {
			
			@Override
			public void onFinish(Object... params) {
				phonelist.remove(usernames);
				usernamelist.remove(posion);
				tv_title.setText("聊天信息("+phonelist.size()+")");
				adapter.notifyDataSetChanged();
				Toast.makeText(GroupDetailActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onFailed(String Message) {
				
			}
		});
		
	}
	
	private void getGroupMemberCache(){
		groups.clear();
		phonelist.clear();
		usernamelist.clear();
		ArrayList<GroupMember> groupmemberlist = SharePreferenceHelper.getGroupsDetail(GroupDetailActivity.this, yonghuID, groupId);
		if(groupmemberlist.size()>0){
			groups.addAll(groupmemberlist);
			tv_title.setText("聊天信息("+groups.size()+")");
			for(int i=0;i<groups.size();i++){
				if(groups.get(i).getMember()==null){
					phonelist.add(groups.get(i).getOwner());
					if(groups.get(i).getOwner().toString().equals(yonghu)){
						btn_tuiqun.setText("退 出 并 删 除 群");
						nun = 0;
					}
				}else{
					phonelist.add(groups.get(i).getMember());
					if(groups.get(i).getMember().toString().equals(yonghu)){
						btn_tuiqun.setText("退 出 群");
						nun = 1;
					}
				}
				usernamelist.add(groups.get(i).getUsername());
			}
		}
	}
	
	private void getGroupMember() {

		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		contactgroupService.getGroupMember(groupId,
				new GetOneRecordListener<List<GroupMember>>() {

			@Override
			public void onFinish(List<GroupMember> data) {
				Log.e("data", data.toString());
				groups.clear();
				phonelist.clear();
				usernamelist.clear();
				if (data != null && data.size() > 0) {
					groups.addAll(data);
					tv_title.setText("聊天信息("+groups.size()+")");
					SharePreferenceHelper.saveGroupsDetail(GroupDetailActivity.this, yonghuID, groupId, data);
					for(int i=0;i<groups.size();i++){
						if(groups.get(i).getMember()==null){
							phonelist.add(groups.get(i).getOwner());
							if(groups.get(i).getOwner().toString().equals(yonghu)){
								btn_tuiqun.setText("退 出 并 删 除 群");
								nun = 0;
							}
						}else{
							phonelist.add(groups.get(i).getMember());
							if(groups.get(i).getMember().toString().equals(yonghu)){
								btn_tuiqun.setText("退 出 群");
								nun = 1;
							}
						}
						usernamelist.add(groups.get(i).getUsername());
					}
				}
				isreqok = true;
				adapter.notifyDataSetChanged();
			}

			@Override
			public void onFailed(String Message) {
				ToastHelper.showMsg(GroupDetailActivity.this, Message, false);
			}
		});
	}
	
	//通过账号获取唯一id
	public void getid(String username){
		if (contactgroupService == null) {
			contactgroupService = new ContactGroupService(this);
		}
		
		contactgroupService.getuUserid(username, new GetMultilParamsListener() {
			

			@Override
			public void onFinish(Object... params) {
				if(params != null){
					LognUser user = (LognUser) params[0];
					groudMemberID = user.getId();
					isgetidOK = true;
				}
			}
			
			@Override
			public void onFailed(String Message) {
				Toast.makeText(GroupDetailActivity.this, Message, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	//获取联系人详情
	private void getContactDetail(final String groupmemberid) {

		if (contactService == null) {
			contactService = new ContactService(getApplicationContext());
		}

		contactService.getContactdetail(yonghuID, groupmemberid,
				new GetOneRecordListener<DetailPerson>() {

					@Override
					public void onFinish(DetailPerson data) {
						homeContactDetailEntity = data;
						if(homeContactDetailEntity.getIs_common().equals("1")||homeContactDetailEntity.getIs_favorite().equals("1")){
							Intent intent = new Intent(GroupDetailActivity.this,HomeContactDeail2Activity.class);
							intent.putExtra("uid", homeContactDetailEntity.getUid());
							intent.putExtra("homeContactDetailEntity", homeContactDetailEntity);
							intent.putExtra("titleback", tv_title.getText().toString().trim());
							startActivity(intent);
//							finish();
						}else{
							Intent intent = new Intent(GroupDetailActivity.this,HomeContactDeail1Activity.class);
//							intent.putExtra("realname", homeContactDetailEntity.getRealname());
//							intent.putExtra("sex", homeContactDetailEntity.getSex());
//							intent.putExtra("account_mobile", homeContactDetailEntity.getAccount_mobile());
//							intent.putExtra("mobile", homeContactDetailEntity.getMobile());
							intent.putExtra("homeContactDetailEntity", homeContactDetailEntity);
							intent.putExtra("yonghuID", yonghuID);
							intent.putExtra("uid", groupmemberid);
							intent.putExtra("titleback", tv_title.getText().toString().trim());
							startActivity(intent);
//							finish();
						}

					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(GroupDetailActivity.this,
								Message, false);
					}
				});
	}
	
	public void back(View view) {
		setResult(RESULT_OK);
		finish();
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lay_groupname:
			changeGroupname();
			break;

		default:
			break;
		}
	}

	private void changeGroupname() {
		Intent intent = new Intent(GroupDetailActivity.this,ChangeGroupnameActivity.class);
		String groupname = group_name.getText().toString().trim();
		intent.putExtra("groupname", groupname);
		intent.putExtra("groupId", groupId);
		startActivityForResult(intent, 5);
	}
	
}
